package com.wgke.bluetooth.view;


import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.Log;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class HeatMapRenderer implements GLSurfaceView.Renderer {
    private static final String TAG = "HeatMapRenderer";

    private Context context;
    private float[][] heatMapData;
    private int rows, cols;

    // 顶点和颜色缓冲区
    private FloatBuffer vertexBuffer;
    private FloatBuffer colorBuffer;
    private int vertexCount;

    // 光源属性
    private final float[] lightPos = {0.0f, 2.0f, 1.0f, 1.0f};
    private final float[] lightAmbient = {0.2f, 0.2f, 0.2f, 1.0f};
    private final float[] lightDiffuse = {0.8f, 0.8f, 0.8f, 1.0f};

    // 材质属性
    private final float[] materialAmbient = {0.5f, 0.5f, 0.5f, 1.0f};
    private final float[] materialDiffuse = {0.8f, 0.8f, 0.8f, 1.0f};

    public HeatMapRenderer(Context context) {
        this.context = context;
        // 初始化默认数据
        heatMapData = HeatMapData.generateSampleData(10, 10);
    }

    public void setHeatMapData(float[][] data) {
        heatMapData = data;
        rows = heatMapData.length;
        cols = heatMapData[0].length;
        generateVertexAndColorData();
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        Log.d(TAG, "onSurfaceCreated called");

        // 设置清屏颜色
        gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

        // 启用深度测试
        gl.glEnable(GL10.GL_DEPTH_TEST);

        // 设置背面剔除
        gl.glEnable(GL10.GL_CULL_FACE);
        gl.glCullFace(GL10.GL_BACK);

        // 启用光照
        gl.glEnable(GL10.GL_LIGHTING);
        gl.glEnable(GL10.GL_LIGHT0);

        // 设置光源属性
        gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightPos, 0);
        gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_AMBIENT, lightAmbient, 0);
        gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, lightDiffuse, 0);

        // 设置材质属性
        gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_AMBIENT, materialAmbient, 0);
        gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_DIFFUSE, materialDiffuse, 0);

        // 生成顶点和颜色数据
        generateVertexAndColorData();
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        Log.d(TAG, "onSurfaceChanged: width=" + width + ", height=" + height);

        // 设置视口
        gl.glViewport(0, 0, width, height);

        // 设置投影矩阵
        float ratio = (float) width / height;
        gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();
        gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        Log.e(TAG, "onDrawFrame start");

        // 清除颜色和深度缓冲区
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

        // 设置模型视图矩阵
        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity();

        // 设置相机位置
        gl.glTranslatef(0.0f, 0.0f, -5.0f);  // 向后移动5个单位
        gl.glRotatef(15, 1, 0, 0);           // 绕X轴旋转15度
        gl.glRotatef(-15, 0, 1, 0);          // 绕Y轴旋转-15度

        // 启用顶点和颜色数组
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL10.GL_COLOR_ARRAY);

        // 设置顶点和颜色数据
        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
        gl.glColorPointer(4, GL10.GL_FLOAT, 0, colorBuffer);

        // 绘制三角形
        gl.glDrawArrays(GL10.GL_TRIANGLES, 0, vertexCount);

        // 禁用顶点和颜色数组
        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
    }

    // 生成顶点和颜色数据
    private void generateVertexAndColorData() {
        if (heatMapData == null || heatMapData.length == 0) {
            return;
        }

        rows = heatMapData.length;
        cols = heatMapData[0].length;
        int pointCount = rows * cols;
        int triangleCount = (rows - 1) * (cols - 1) * 2;
        vertexCount = triangleCount * 3; // 每个三角形3个顶点

        float[] vertices = new float[vertexCount * 3]; // 每个顶点3个坐标
        float[] colors = new float[vertexCount * 4];   // 每个顶点4个颜色值（RGBA）

        int vertexIndex = 0;
        int colorIndex = 0;

        for (int i = 0; i < rows - 1; i++) {
            for (int j = 0; j < cols - 1; j++) {
                // 计算当前网格单元的4个顶点索引
                int topLeft = i * cols + j;
                int topRight = i * cols + j + 1;
                int bottomLeft = (i + 1) * cols + j;
                int bottomRight = (i + 1) * cols + j + 1;

                // 三角形1：topLeft, bottomLeft, topRight
                addVertex(vertices, vertexIndex++, i, j, heatMapData[i][j]);
                addVertex(vertices, vertexIndex++, i + 1, j, heatMapData[i + 1][j]);
                addVertex(vertices, vertexIndex++, i, j + 1, heatMapData[i][j + 1]);

                // 三角形2：topRight, bottomLeft, bottomRight
                addVertex(vertices, vertexIndex++, i, j + 1, heatMapData[i][j + 1]);
                addVertex(vertices, vertexIndex++, i + 1, j, heatMapData[i + 1][j]);
                addVertex(vertices, vertexIndex++, i + 1, j + 1, heatMapData[i + 1][j + 1]);

                // 添加颜色（根据热力值映射）
                addColor(colors, colorIndex++, heatMapData[i][j]);
                addColor(colors, colorIndex++, heatMapData[i + 1][j]);
                addColor(colors, colorIndex++, heatMapData[i][j + 1]);

                addColor(colors, colorIndex++, heatMapData[i][j + 1]);
                addColor(colors, colorIndex++, heatMapData[i + 1][j]);
                addColor(colors, colorIndex++, heatMapData[i + 1][j + 1]);
            }
        }

        // 创建顶点缓冲区
        ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
        vbb.order(ByteOrder.nativeOrder());
        vertexBuffer = vbb.asFloatBuffer();
        vertexBuffer.put(vertices);
        vertexBuffer.position(0);

        // 创建颜色缓冲区
        ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * 4);
        cbb.order(ByteOrder.nativeOrder());
        colorBuffer = cbb.asFloatBuffer();
        colorBuffer.put(colors);
        colorBuffer.position(0);
    }

    // 添加顶点坐标（x,y对应网格位置，z对应热力值高度）
    private void addVertex(float[] vertices, int index, int row, int col, float heatValue) {
        float x = (float) col / (cols - 1) * 2 - 1;
        float y = (float) row / (rows - 1) * 2 - 1;
        float z = heatValue * 0.5f; // 热力值映射为高度

        vertices[index * 3] = x;
        vertices[index * 3 + 1] = y;
        vertices[index * 3 + 2] = z;
    }

    // 添加颜色（热力值到颜色的映射：蓝-黄-红-白渐变）
    private void addColor(float[] colors, int index, float heatValue) {
        float r, g, b;
        if (heatValue < 0.3f) {
            r = 0;
            g = heatValue * 3.3f;
            b = 1; // 蓝色
        } else if (heatValue < 0.6f) {
            r = 0;
            g = 1;
            b = 1 - (heatValue - 0.3f) * 3.3f; // 蓝到黄
        } else if (heatValue < 0.8f) {
            r = (heatValue - 0.6f) * 5;
            g = 1;
            b = 0; // 黄到红
        } else {
            r = 1;
            g = 1 - (heatValue - 0.8f) * 5;
            b = 0; // 红到白
        }

        colors[index * 4] = r;
        colors[index * 4 + 1] = g;
        colors[index * 4 + 2] = b;
        colors[index * 4 + 3] = 1.0f; // 不透明
    }
}